#encoding:utf-8
from app import app, request, jsonify, session, db,render_template,redirect,url_for
from app.common.common import res_json, base_url,res_sucss,res_msg
import time
from app.models.shop_list import *
from app.models.cusotmer import *
from app.controller.saveImg import save_img
from app.controller.token import certify_token,generate_token,login_required


#用于接收图片文件api
@app.route('/api/v1/admin/save_img',methods=['POST'])
def save_imgs():
    img_file = request.files.get('img_file') or None
    if img_file == None or img_file == '':
        return res_msg(201,'没有图片文件')
    s = save_img(img_file,'/static/img/upload/')
    url = s.save()
    return res_json(200,{'url':base_url + url},'操作成功')


#商户注册
@app.route('/api/v1/admin/register',methods=['POST'])
def register():
    username = request.form.get('username')
    password = request.form.get('password')
    user = Shop_list.query.filter_by(userName=username).first()
    if user:
        return res_msg('201','用户已存在，请直接登录')
    shop_item = Shop_list(userName=username)
    shop_item.hash_password(password)
    info_item = Shop_info(shop_id=username)
    db.session.add(info_item)
    db.session.add(shop_item)
    db.session.commit()
    return res_msg(200,'注册成功')

#商户登录
@app.route('/api/v1/admin/login',methods=['POST'])
def login():
    username = request.form.get('username')
    password = request.form.get('password')
    obj = Shop_list.query.filter_by(userName=username).first()
    if not obj:
        return res_json(201,'','未找到该用户')
    if obj.verify_password(password):
        token = generate_token(username)
        return res_json(200,{'token':token,'user':username},'登录成功')
    else:
        return res_json(201,'','密码错误')
#获取商户信息接口
@app.route('/api/v1/admin/get_shopinfo',methods=['POST'],endpoint='get_shopinfo')
@login_required
def get_shopinfo(user):
    info_item = Shop_info.query.filter_by(shop_id=user).first()
    news = len(Order_list.query.filter_by(shopId=user,orderStatus=1).all())
    res_datas={
        'avatar':base_url + info_item.avatar,
        'bulletin':info_item.bulletin,
        'deliveryprice':info_item.deliveryPrice,
        'minprice':info_item.minPrice,
        'name':info_item.name,
        'deliverytime':info_item.deliveryTime,
        'news_len':news
    }
    return res_json('200',res_datas,'操作成功')


#商户信息修改接口
@app.route('/api/v1/admin/edit_shopinfo',methods=['POST'],endpoint='edit_shopinfo')
@login_required
def edit_shopinfo(user):
    avatar = request.form.get('avatar')
    bulletin = request.form.get('bulletin')
    deliveryprice = request.form.get('deliveryprice')
    name = request.form.get('name')
    minprice = request.form.get('minprice')
    deliverytime = request.form.get('deliverytime')
    info_item = Shop_info.query.filter_by(shop_id=user).first()
    info_item.avatar =  avatar
    info_item.bulletin = bulletin
    info_item.deliveryPrice = deliveryprice
    info_item.name = name
    info_item.minPrice = minprice
    info_item.deliveryTime = deliverytime
    db.session.commit()
    return res_sucss()

#添加分类菜单
@app.route('/api/v1/admin/add_menu',methods=['POST'])
@login_required
def add_menu(user):
    name = request.form.get('name')
    menu_type = request.form.get('menu_type') or -1
    save = Goods_class(name=name,type=menu_type,shop_id=user)
    db.session.add(save)
    db.session.commit()
    return res_sucss()

#返回分类菜单
@app.route('/api/v1/admin/get_menu',methods=['POST'],endpoint='get_menu')
@login_required
def get_menu(user):
    obj = Goods_class.query.all()
    arry = []
    for item in obj:
        arry.append({
            'id':item.id,
            'name':item.name,
            'type':item.type
        })
    return res_json('200',arry,'操作成功')

#删除分类
@app.route('/api/v1/admin/del_menu',methods=['POST'],endpoint='del_menu')
@login_required
def del_menu(user):
    class_id = request.form.get('class_id')
    obj = Goods_class.query.filter_by(id=class_id).first()
    db.session.delete(obj)
    db.session.commit()
    return res_sucss()

#商户商品  点击分类跳转商品list
@app.route('/api/v1/admin/get_shop_goods',methods=['POST'])
def get_shop_goods():
    class_id = request.form.get('class_id') or None
    if class_id == None:
        return res_msg('201','无class_id')
    result = Goods.query.filter_by(class_id=class_id).order_by(Goods.id.desc())
    resArr = []
    for item in result:
        resArr.append({
                'id':item.id,
                'name':item.name,
                'Icon':base_url + item.Icon,
                'oldPrice':item.oldPrice,
                'price':item.price,
                'description':item.description,
                'sellCount':item.sellCount
            })
    return jsonify({
        'code':200,
        'data':resArr,
        'cunt':Goods_list.query.count()
    })

#新增/编辑商品 商户商品
@app.route('/api/v1/admin/add_shop_goods',methods=['POST'],endpoint='add_shop_goods')
@login_required
def add_shop_goods(user):
    goods_name = request.form.get('name')
    description = request.form.get('description')
    img_url = request.form.get('img_url')
    oldprice = request.form.get('oldPrice') or 0 
    price = request.form.get('price') or 0
    product_id = request.form.get('id') or None
    class_id = request.form.get('class_id') or None

    if product_id == None or product_id == '':
        save = Goods(name=goods_name,Icon=img_url,oldPrice=oldprice,price=price,description=description,class_id=class_id)
        db.session.add(save)
        db.session.commit()
        return res_sucss()
    else:
        obj = Goods.query.filter_by(id=product_id).first()
        obj.Icon = img_url
        obj.name = goods_name
        obj.oldPrice = oldprice
        obj.price = price
        obj.description = description
        db.session.commit()
        return res_sucss()

#删除商品 商户商品
@app.route('/api/v1/admin/del_shop_good',methods=['POST'],endpoint='del_shop_good')
def del_shop_good():
    good_id = request.form.get('good_id')
    obj = Goods.query.filter_by(id=good_id).first()
    db.session.delete(obj)
    db.session.commit()
    return res_sucss()

#新增/编辑商品 公共库商品
@app.route('/api/v1/admin/add_goods',methods=['POST'])
def add_goods():
    product_img = request.files.get('product_img')
    goods_name = request.form.get('goods_name')
    description = request.form.get('description')
    oldprice = request.form.get('oldprice') or 0 
    price = request.form.get('price') or 0
    product_id = request.form.get('id') or None
    if not product_img == None:
        s = save_img(product_img,'/static/img/upload/')
        url = s.save()
    else:
        url = None
 
    if product_id == None:
        save = Goods_list(name=goods_name,Icon=url,oldPrice=oldprice,price=price,description=description)
        db.session.add(save)
        db.session.commit()
        return res_sucss()
    else:
        obj = Goods_list.query.filter_by(id=product_id).first()
        if not url == None:
            obj.Icon = url
        obj.name = goods_name
        obj.oldPrice = oldprice
        obj.price = price
        obj.description = description
        db.session.commit()
        return res_sucss()

#从公共库添加商品接口
@app.route('/app/v1/admin/add_goods_common',methods=['POST'],endpoint='add_goods_common')
@login_required
def add_goods_common(user):
    goods_id = request.form.get('goods_id')
    class_id = request.form.get('class_id')
    good = Goods_list.query.filter_by(id = goods_id).first()
    saveGood = Goods(name=good.name,Icon=good.Icon,oldPrice=good.oldPrice,price=good.price,description=good.description,class_id=class_id)
    db.session.add(saveGood)
    db.session.commit()
    return res_sucss()

#商品列表 公共库商品
@app.route('/api/v1/admin/get_goods',methods=['POST'])
def get_goods():
    page_now = request.form.get('page_now') or 1
    resArr = []
    page = 12
    num = (int(page_now)-1)*page
    obj = Goods_list.query.offset(num).limit(page).all()
    for item in obj:
        resArr.append({
                'id':item.id,
                'name':item.name,
                'Icon':base_url + item.Icon,
                'oldPrice':item.oldPrice,
                'price':item.price,
                'description':item.description,
                'sellCount':item.sellCount
            })
    return jsonify({
        'code':200,
        'data':resArr,
        'cunt':Goods_list.query.count()
    })

#确认接单
@app.route('/api/v1/admin/receipt_order',methods=['POST'],endpoint='receipt_order')
@login_required
def receipt_order(user):
    orderNo = request.form.get('orderNo') or None
    if orderNo == None:
        return res_msg(201,'参数错误')
    app.logger.info('商户%s 确认接单  订单号： %s' % (user,orderNo))
    orderItem = Order_list.query.filter_by(orderNo=orderNo).first()
    orderItem.orderStatus = 2
    db.session.commit()
    return res_sucss()

#删除商品 公共库商品
@app.route('/api/v1/admin/del_good',methods=['POST'])
def del_good():
    good_id = request.form.get('good_id')
    obj = Goods_list.query.filter_by(id=good_id).first()
    db.session.delete(obj)
    db.session.commit()
    return res_sucss()




